<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 第一行 -->
      <el-row :gutter="15">
        <!-- 第一列搜索框 -->
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="UserInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 第二列：添加用户 -->
        <el-col :span="4">
          <el-button type="primary" @click="addUserdialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <!-- 作用域插槽 -->
        <el-table-column label="状态">
          <template slot-scope="scope">
            <!-- {{ scope.row }} -->
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)">
            </el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)">
            </el-button>

            <el-tooltip effect="dark" content="设置权限" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)">
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="UserInfo.pagenum" :page-sizes="[1, 2, 3, 5]" :page-size="UserInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>

      <!-- 添加用户对话框区域 -->
      <el-dialog title="添加用户" :visible.sync="addUserdialogVisible" width="50%" @close="addDialogClose">
        <!-- 表单内容验证区域 -->
        <el-form :model="addForm" :rules="addFormrules" ref="ruleFormRef" label-width="80px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addUserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers"> 确 定 </el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框区域 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
        <!-- 修改用户表单内容 -->
        <el-form :model="eidtForm" :rules="eidtFormRules" ref="ruleFormRef" label-width="70px">
          <el-form-item label="用户名称">
            <el-input v-model="eidtForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="eidtForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="eidtForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUsers">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 设置权限对话框 -->
      <el-dialog title="设置角色" :visible.sync="setRoleDialogVisible" width="50%" @close="closeRoleDilogVisible">
        <div>
          <p>当前的用户：{{ userInfo.username }}</p>
          <p>当前的角色：{{ userInfo.role_name }}</p>
          <p>
            分配新角色:
            <el-select v-model="selectRoulId" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 校验邮箱是否合法
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      // 如果验证通过
      if (regEmail.test(value)) return cb()
      // 验证不合法
      cb(new Error('请输入合法的邮箱'))
    }
    // 校验手机是否合法
    var checkMobile = (rule, value, cb) => {
      // 手机验证正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      // 如果验证通过
      if (regMobile.test(value)) return cb()
      // 如果验证失败
      cb(new Error('请输入合法的手机号'))
    }
    return {
      UserInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        pagesize: 2,
      },
      userList: [],
      total: 0,
      // 隐藏添加用户对话框
      addUserdialogVisible: false,
      // 添加表单用户数据内容
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加表单用户规则
      addFormrules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 6, message: '用户名长度在3-6个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码长度在6-15个字符', trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 隐藏修改用户对话框
      editDialogVisible: false,
      // 保存查询的用户信息
      eidtForm: {},
      // 检验编辑用户规格
      eidtFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },

      // 设置权限对话框id
      setRoleDialogVisible: false,

      // 需要设置权限的用户信息
      userInfo: {},
      // 设置权限用户信息的权限列表
      rolesList: [],
      // 设置权限对话框中：分配角色下拉已选中的角色id值
      selectRoulId: '',
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 发送get请求获取用户列表
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.UserInfo,
      })
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 监听n条每页
    handleSizeChange(newSize) {
      console.log(newSize)
      this.UserInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听当前处在第几页
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.UserInfo.pagenum = newPage
      this.getUserList()
    },
    async userStateChange(userInfo) {
      console.log(userInfo)
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        res.meta.status = !res.meta.status
        return this.$message.error('修改用户状态失败')
      }
      this.$message.success('更新用户状态成功')
    },
    // 监听添加用户对话框关闭事件
    addDialogClose() {
      this.$refs.ruleFormRef.resetFields()
      console.log(this.$refs)
    },
    // 点击确定按钮，增加表单预校验
    addUsers() {
      this.$refs.ruleFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        // 可以发起添加用户网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加用户失败')
        }
        this.$message.success('添加用户成功')
        // 关闭添加用户对话框
        this.addUserdialogVisible = false
        // 重新获取用户列表页面
        this.getUserList()
      })
    },
    // 修改用户信息
    async showEditDialog(id) {
      //  console.log(id)

      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.eidtForm = res.data
      this.editDialogVisible = true //打开修改对话框
    },
    // 监听修改表单关闭
    editDialogClosed() {
      this.$refs.ruleFormRef.resetFields()
    },
    // 点击确定 对修改表单信息预验证
    editUsers(id) {
      this.$refs.ruleFormRef.validate(async (valid) => {
        // console.log(valid)
        console.log(id)
        if (!valid) return
        // 发起修改用户请求
        const { data: res } = await this.$http.put(
          'users/' + this.eidtForm.id,
          { email: this.eidtForm.email, mobile: this.eidtForm.mobile }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败')
        }
        //如果修改成功 关闭修改对话框
        this.editDialogVisible = false
        // 重新渲染用户页面
        this.getUserList()
        // 提示修改成功
        this.$message.success('修改用户信息成功!')
      })
    },
    // 删除按钮功能
    async removeUserById(id) {
      // console.log(id)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(confirmResult) //取消返回的是：cancel  确定返回:confirm
      if (confirmResult !== 'confirm') return this.$message.info('取消删除用户')
      // 如果点击确认删除发送删除请求
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },

    // 设置权限
    async setRole(userInfo) {
      // 保存用户信息
      this.userInfo = userInfo
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },

    // 分配角色
    async saveRoleInfo() {
      if (this.selectRoulId === '') {
        return this.$message.error('请选择分配新角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.selectRoulId,
        }
      )
      if (res.meta.status !== 200) {
        return this.res.meta.msg
      }
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听关闭角色对话框的关闭事件：清空已选的角色
    closeRoleDilogVisible() {
      this.selectRoulId = ''
      this.userInfo = {}
    },
  },
}
</script>

<style lang="less" scoped>
</style>